#include "List.h"
LTNode* LTInit()
{
	LTNode* phead = (LTNode*)malloc(sizeof(LTNode));
	phead->data = -1;
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
static bool LTEmpty(LTNode* phead)
{
	if (phead->next == phead)	
	     return true;
	 return false;
}
static LTNode* BuyLTNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}
void LTPrint(LTNode* phead)
{
	printf("head<=>");
	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("head\n");
}
void LTPushBack(LTNode* phead, LTDataType x)
{
	LTInsert(phead, x);
	/*assert(phead);
	LTNode* newnode = BuyLTNode(x);
	LTNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/
}
void LTPushFront(LTNode* phead, LTDataType x)
{
	LTInsert(phead->next, x);
	/*assert(phead);
	LTNode* newnode = BuyLTNode(x);
	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;*/
}
void LTPopBack(LTNode* phead)
{
	
	assert(phead);
	assert(!LTEmpty(phead));
    LTErase(phead->prev);
	/*LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;
	tailprev -> next = phead;
	phead->prev = tailprev;
	free(tail);*/
}
void LTPopFront(LTNode* phead)
{
	
	assert(phead);
	assert(!LTEmpty(phead));
	LTErase(phead->next);
	/*LTNode* next = phead->next->next;
	free(phead->next);
	phead->next = next;
	next->prev = phead;*/
}
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	assert(!LTEmpty(phead));
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}
void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newnode = BuyLTNode(x);
	LTNode* prev = pos->prev;

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}
void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* prev = pos->prev;
	LTNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}
void LTDestory(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}
